package Server.service.impl;

import Server.dao.DictionarysDao;
import Server.entity.Diction;
import Server.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class RedisServiceImpl implements RedisService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private DictionarysDao dictionaryDao;
    @Override
    public void deleted(String key) {
        redisTemplate.delete(key);
    }

    @Override
    public void deleted(Collection<String> keys) {
        redisTemplate.delete(keys);
    }

    @Override
    public byte[] dump(String key) {
        return redisTemplate.dump(key);
    }

    @Override
    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    @Override
    public Boolean expire(String key, long timeout, TimeUnit unit) {
        return redisTemplate.expire(key, timeout, unit);
    }

    @Override
    public Boolean expire(String key, Date date) {
        return redisTemplate.expireAt(key, date);
    }

    @Override
    public Set<String> keys(String pattern) {
        return redisTemplate.keys(pattern);
    }

    @Override
    public boolean set(String key, String value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean set(String key, String value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public long getTime() {
        Diction dictionary=dictionaryDao.findByKeyst("token");
        return Long.parseLong(dictionary.getVal());
    }

    @Override
    public String get(String key) {
        return redisTemplate.opsForValue().get(key);
    }
}
